package com.my.lucky.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.my.lucky.model.Filter;
import com.my.lucky.service.FilterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@RestController
@RequestMapping("/api/filters")
public class FilterController {

    private final FilterService filterService;
    private final ObjectMapper objectMapper;

    @Autowired
    public FilterController(FilterService filterService, ObjectMapper objectMapper) {
        this.filterService = filterService;
        this.objectMapper = objectMapper;
    }

    /**
     * 获取所有保存的过滤条件
     */
    @GetMapping
    public List<Filter> getAllFilters() {
        return filterService.getAllFilters();
    }

    /**
     * 根据ID获取过滤条件
     */
    @GetMapping("/{id}")
    public ResponseEntity<Filter> getFilterById(@PathVariable Long id) {
        Optional<Filter> filter = filterService.getFilterById(id);
        return filter.map(ResponseEntity::ok)
                .orElseGet(() -> ResponseEntity.notFound().build());
    }

    /**
     * 创建新的过滤条件
     */
    @PostMapping
    public ResponseEntity<Filter> createFilter(@RequestBody Map<String, Object> filterData) {
        try {
            // 提取必要的字段
            String name = (String) filterData.get("name");
            String description = (String) filterData.get("description");
            Map<String, Object> conditions = (Map<String, Object>) filterData.get("conditions");

            // 将条件转换为JSON字符串
            String conditionsJson = objectMapper.writeValueAsString(conditions);

            // 创建Filter对象
            Filter filter = new Filter();
            filter.setName(name);
            filter.setDescription(description);
            filter.setConditions(conditionsJson);

            // 保存并返回
            Filter savedFilter = filterService.saveFilter(filter);
            return new ResponseEntity<>(savedFilter, HttpStatus.CREATED);
        } catch (Exception e) {
            return new ResponseEntity<>(null, HttpStatus.BAD_REQUEST);
        }
    }

    /**
     * 更新过滤条件
     */
    @PutMapping("/{id}")
    public ResponseEntity<Filter> updateFilter(
            @PathVariable Long id,
            @RequestBody Map<String, Object> filterData) {
        try {
            // 提取必要的字段
            String name = (String) filterData.get("name");
            String description = (String) filterData.get("description");
            Map<String, Object> conditions = (Map<String, Object>) filterData.get("conditions");

            // 将条件转换为JSON字符串
            String conditionsJson = objectMapper.writeValueAsString(conditions);

            // 创建Filter对象
            Filter filter = new Filter();
            filter.setName(name);
            filter.setDescription(description);
            filter.setConditions(conditionsJson);

            // 更新并返回
            Filter updatedFilter = filterService.updateFilter(id, filter);
            return ResponseEntity.ok(updatedFilter);
        } catch (Exception e) {
            return new ResponseEntity<>(null, HttpStatus.BAD_REQUEST);
        }
    }

    /**
     * 删除过滤条件
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Map<String, Boolean>> deleteFilter(@PathVariable Long id) {
        try {
            filterService.deleteFilter(id);
            Map<String, Boolean> response = new HashMap<>();
            response.put("deleted", Boolean.TRUE);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Boolean> response = new HashMap<>();
            response.put("deleted", Boolean.FALSE);
            return ResponseEntity.ok(response);
        }
    }

}